﻿//-------------------------------------------------------------------------------------------------
// <copyright file="ContentConfigurationSerializer.cs" company="Anthony Adam">
// Copyright (c) Anthony Adam 2015. All rights reserved.
// </copyright>
//-------------------------------------------------------------------------------------------------
namespace SuperStarRounds.Classes.FileIO
{
  using System;
  using System.IO;
  using System.Runtime.Serialization.Formatters.Binary;

  using Models;

  /// <summary>
  /// Serializer that does the IO for the file saving and loading.
  /// </summary>
  public static class ContentConfigurationSerializer
  {
    /// <summary>
    /// Save content configuration.
    /// </summary>
    /// <param name="filename">Fully qualified content configuration filename</param>
    /// <param name="itemToSerialize">Instance of content configuration settings</param>
    public static void SerializeContentInclusions(string filename, ContentInclusions itemToSerialize)
    {
      var stream = File.Open(filename, FileMode.Create);
      var binaryFormatter = new BinaryFormatter();
      try
      {
        binaryFormatter.Serialize(stream, itemToSerialize);
        stream.Close();
      }
      catch (Exception)
      {
        // if serialize fails, close the stream
        stream.Close();
      }
    }

    /// <summary>
    /// Load content configuration.
    /// </summary>
    /// <param name="filename">Fully qualified content configuration filename</param>
    /// <returns>Content configurations instance</returns>
    public static ContentInclusions DeserializeContentInclusions(string filename)
    {
      if (!File.Exists(filename)) return new ContentInclusions();

      var stream = File.Open(filename, FileMode.Open);
      var binaryFormatter = new BinaryFormatter();
      try
      {
        var itemDeSerialized = (ContentInclusions) binaryFormatter.Deserialize(stream);
        stream.Close();
        return itemDeSerialized;
      }
      catch (Exception)
      {
        stream.Close();
        return new ContentInclusions();
      }
    }
  }
}
